package com.westvalley.syn.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import weaver.hrm.company.SubCompanyComInfo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.westvalley.common.kit.SqlsKit;
import com.westvalley.common.kit.StringKit;
import com.westvalley.common.kit.SqlsKit.SqlOperateType;
import com.westvalley.common.result.SqlResult;
import com.westvalley.syn.bean.Result;
import com.westvalley.service.cache.HrSubcompanyDefinedCache;
import com.westvalley.service.cache.OrgLeftMenuConfigCache;
import com.westvalley.service.cache.OrgMainMenuConfigCache;
import com.westvalley.service.cache.OrgSubCompanyCache;

/**
 * 分部信息同步
 * @author mos
 *
 */
public class HrSubCompanyService extends SynService{
	private static final String KEY = "comp";
	public static final String INSERT_LEFT_MENU_SQL = "insert into leftmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e)  select  distinct  userid,infoid,visible,viewindex,{subcompanyId},2,locked,lockedbyid,usecustomname,customname,customname_e from leftmenuconfig where resourcetype=1  and resourceid=1";
	public static final String INSERT_MAIN_MENU_SQL = "insert into mainmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e)  select  distinct  userid,infoid,visible,viewindex,{subcompanyId},2,locked,lockedbyid,usecustomname,customname,customname_e from mainmenuconfig where resourcetype=1  and resourceid=1";
	private OrgSubCompanyCache subCompanyCache = OrgSubCompanyCache.me();
	private HrSubcompanyDefinedCache subcompanyDefinedCache = HrSubcompanyDefinedCache.me();
	private OrgLeftMenuConfigCache leftMenuConfigCache = OrgLeftMenuConfigCache.me();
	private OrgMainMenuConfigCache mainMenuConfigCache = OrgMainMenuConfigCache.me();
	
	public HrSubCompanyService(){
		refreshCache();
		this.url = prop.getPropValue(KEY);
	}
	
	@Override
	protected void initParams(Map<String, String> params) {
		params.put("shopId", "TSG1");
	}
	

	@Override
	protected Result synMainData(JSONArray jsonArrData) {
		Iterator<Object> it;
		if(jsonArrData!=null && (it=jsonArrData.iterator())!=null){
			SqlResult sqlResultInsert = SqlResult.me();
			SqlResult sqlResultUpdate = SqlResult.me();
			while (it.hasNext()) {
				JSONObject ob = (JSONObject) it.next();
				if( ob!=null ){
					String compid = ob.getString("id");	//分部编码
					if( StrKit.notBlank(compid) ){
						Record subCompanyRecord = this.subCompanyCache.getRecordByCode(compid);	//缓存中分部信息
						if( subCompanyRecord==null ){
							sqlResultInsert.set(insertData(compid,ob));
						}else{
							sqlResultUpdate.set(updateData(compid,ob));
						}
					}else{
						return Result.me(new RuntimeException("数据主键为空！"));
					}
				}else{
					return Result.me(new RuntimeException("数据解析失败！"));
				}
			}
			int[] insertNums = sqlResultInsert.batch(500);
			int[] updateNums = sqlResultUpdate.batch(500);
			return Result.me(jsonArrData.size(),insertNums,updateNums);
		}else{
			return Result.me(new RuntimeException("接口数据为空无法同步！"));
		}
	}

	@Override
	protected Result synpOtherData(Result result, JSONArray jsonArrData) {
		if(result!=null && result.isFlag()){
			Iterator<Object> it;
			if(jsonArrData!=null && (it=jsonArrData.iterator())!=null){
				List<String> insertLeftMenuSqlList = new ArrayList<String>();
				List<String> insertMainMenuSqlList = new ArrayList<String>();
				SqlResult sqlResultUpdateRowData = SqlResult.me();
				SqlResult sqlResultInsertSubCompanyDefined = SqlResult.me();
				SqlResult sqlResultUpdateSubCompanyDefined = SqlResult.me();
				while (it.hasNext()) {
					JSONObject ob = (JSONObject) it.next();
					if( ob!=null ){
						String compid = ob.getString("id");	//分部编码
						Record subCompanyRecord = this.subCompanyCache.getRecordByCode(compid);	//缓存中分部信息
						String subCompanyId = StringKit.null2o(subCompanyRecord.get("id"));	//分部ID
						Record subCompanyDefinedRecord = this.subcompanyDefinedCache.getRecordByCode(subCompanyId);	//分部自定义信息
						//上级分部，主菜单，左侧菜单
						if( StrKit.notBlank(compid,subCompanyId) ){
							sqlResultUpdateRowData.set(updateParentData(compid,ob));		
							Record leftMenuRecord = leftMenuConfigCache.getRecordByCode(compid);	//缓存中分部的左侧菜单信息
							if(leftMenuRecord==null)
								insertLeftMenuSqlList.add(insertLeftMenuData(subCompanyId));
							Record mainMenuRecord = mainMenuConfigCache.getRecordByCode(compid);	//缓存中分部的主菜单信息
							if(mainMenuRecord==null)
								insertMainMenuSqlList.add(insertMainMenuData(subCompanyId));
						}
						//分部自定义信息
						if(subCompanyDefinedRecord==null){
							sqlResultInsertSubCompanyDefined.set(insertHrmSubcompanyDefined(subCompanyId, ob));
						}else{
							sqlResultUpdateSubCompanyDefined.set(updateHrmSubcompanyDefined(subCompanyId, ob));
						}
						
					}
				}
				sqlResultUpdateRowData.batch(500);					//更新分部上级
				Db.batch(insertLeftMenuSqlList, 500);				//插入新增分部左侧菜单
				Db.batch(insertMainMenuSqlList, 500);				//插入新增分部主菜单
				sqlResultInsertSubCompanyDefined.batch(500);
				sqlResultUpdateSubCompanyDefined.batch(500);
			}
		}
		return result;
	}
	
	@Override
	protected void refreshCache() {
		this.subCompanyCache.reload();
		this.subcompanyDefinedCache.reload();
		this.leftMenuConfigCache.reload();
		this.mainMenuConfigCache.reload();
		try{new SubCompanyComInfo().removeCompanyCache();}catch (Exception e) {}
	}
	
	/**
	 * 新增数据
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit insertData(String pk,JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();
		sqlsKit.setTableName("HrmSubCompany");
		sqlsKit.addData("companyid", StringKit.null2Str("1"));															//总部id
		sqlsKit.addData("subcompanydesc", StringKit.null2Str(ob.getString("fullName")));								//分部全称
		sqlsKit.addData("subcompanyname", StringKit.null2Str(ob.getString("name")));									//分部简称
		sqlsKit.addData("canceled", StringKit.equals(StringKit.null2Str(ob.getString("enable")), "1")?"0":"1");			//状态
		sqlsKit.addData("subcompanycode", StringKit.null2Str(ob.getString("id")));										//编码
		sqlsKit.setOperateType(SqlOperateType.INSERT);
		return sqlsKit;
	}
	
	/**
	 * 新增左侧系统菜单
	 * @param subCompanyId
	 * @param ob
	 * @return
	 */
	private String insertLeftMenuData(String subCompanyId){
		return INSERT_LEFT_MENU_SQL.replace("{subcompanyId}", subCompanyId);
	}
	
	/**
	 * 新增主系统菜单
	 * @param subCompanyId
	 * @return
	 */
	private String insertMainMenuData(String subCompanyId){
		return INSERT_MAIN_MENU_SQL.replace("{subcompanyId}", subCompanyId);
	}
	
	/**
	 * 更新数据
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit updateData(String pk,JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();
		sqlsKit.setTableName("HrmSubCompany");
		sqlsKit.addData("subcompanydesc", StringKit.null2Str(ob.getString("fullName")));								//分部全称
		sqlsKit.addData("subcompanyname", StringKit.null2Str(ob.getString("name")));									//分部简称
		sqlsKit.addData("canceled", StringKit.equals(StringKit.null2Str(ob.getString("enable")), "1")?"0":"1");			//状态
		sqlsKit.setWhere("subcompanycode", StringKit.null2Str(pk));														//编码
		sqlsKit.setOperateType(SqlOperateType.UPDATE);
		return sqlsKit;
	}
	
	/**
	 * 更新上级数据
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit updateParentData(String pk,JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();
		sqlsKit.setTableName("HrmSubCompany");
		String parentId = ob.getString("headId");
		Record subCompanyRecord = this.subCompanyCache.getRecordByCode(parentId);		//缓存中分部信息
		String supsubcomid = StringKit.null2o(subCompanyRecord.get("id"));
		String supsubCode = StringKit.null2o(subCompanyRecord.get("subcompanycode"));
		if(StringKit.equals(supsubCode, pk))
			supsubcomid = "0";
		sqlsKit.addData("supsubcomid", supsubcomid);									//上级分部id
		sqlsKit.setWhere("subcompanycode", StringKit.null2Str(pk));						//编码
		sqlsKit.setOperateType(SqlOperateType.UPDATE);
		return sqlsKit;
	}
	
	/**
	 * 新增部门自定义信息
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit insertHrmSubcompanyDefined(String pk,JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();
		sqlsKit.setTableName("HrmSubcompanyDefined");
		sqlsKit.addData("ywShopId", StringKit.null2Str(ob.getString("ywShopId")));	//业务店号
		sqlsKit.addData("areaId", StringKit.null2Str(ob.getString("areaId")));		//所属区域
		sqlsKit.addData("shopType", StringKit.null2Str(ob.getString("shopType")));
		sqlsKit.addData("subcomid", pk);
		sqlsKit.setOperateType(SqlOperateType.INSERT);
		return sqlsKit;
	}
	
	/**
	 * 更新部门自定义信息
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit updateHrmSubcompanyDefined(String pk,JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();
		sqlsKit.setTableName("HrmSubcompanyDefined");
		sqlsKit.addData("ywShopId", StringKit.null2Str(ob.getString("ywShopId")));	//业务店号
		sqlsKit.addData("areaId", StringKit.null2Str(ob.getString("areaId")));		//所属区域
		sqlsKit.addData("shopType", StringKit.null2Str(ob.getString("shopType")));
		sqlsKit.setWhere("subcomid", pk);
		sqlsKit.setOperateType(SqlOperateType.UPDATE);
		return sqlsKit;
	}
}
